﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Courier.ItemProviders;
using Umbraco.Courier.Core;

namespace Contour.Addons.CourierSupport.DataResolvers
{
    public class FormMacro : ItemDataResolverProvider
    {
        private static List<string> macroDataTypes = Context.Current.Settings.GetConfigurationCollection("/configuration/itemDataResolvers/macros/add", true);

        public override List<Type> ResolvableTypes
        {
            get { return new List<Type>() { typeof(ContentPropertyData), typeof(Template) }; }
        }

        public override bool ShouldExecute(Item item, Umbraco.Courier.Core.Enums.ItemEvent itemEvent)
        {
            if (item.GetType() == typeof(Template) && (itemEvent == Umbraco.Courier.Core.Enums.ItemEvent.Extracting || itemEvent == Umbraco.Courier.Core.Enums.ItemEvent.Packaged))
                return true;
            else if (item.GetType() == typeof(ContentPropertyData))
            {
                ContentPropertyData cpd = (ContentPropertyData)item;
                foreach (var cp in cpd.Data)
                    if (cp.Value != null && macroDataTypes.Contains(cp.DataTypeEditor.ToString().ToLower()))
                        return true;
            }
            return false;
        }

        public override void Packaging(Item item)
        {
            if (item.GetType() == typeof(ContentPropertyData))
            {
                ContentPropertyData cpd = (ContentPropertyData)item;
                foreach (var prop in cpd.Data.Where(x => x.Value != null && macroDataTypes.Contains(x.DataTypeEditor.ToString().ToLower())))
                {
                    string content = prop.Value.ToString();

                    AddFormDependencies(content, item);
                }
            }         
        }

        public override void PackagedResource(Type itemType, ItemIdentifier itemId, Resource resource)
        {
            if (itemType == typeof(Template) && resource.PackageFromPath.ToLower().EndsWith(".master"))
            {
                var item = PersistenceManager.Default.RetrieveItem<Template>(itemId);
                var encoding = Umbraco.Courier.Core.Settings.Encoding;

                var contents = resource.ResourceContents;
                var content = encoding.GetString(contents);

                AddFormDependencies(content, item);
            }
        }

        private void AddFormDependencies(string content, Item item)
        {
            var macroTags = Umbraco.Courier.Core.Helpers.Dependencies.ReferencedMacrosInstring(content);

            foreach (var tag in macroTags.Where(x => x.Alias == "umbracoContour.RenderForm").ToList())
            {
                Guid guid;

                if (tag.Attributes.ContainsKey("formguid") && !string.IsNullOrEmpty(tag.Attributes["formguid"]) && Guid.TryParse(tag.Attributes["formguid"], out guid))
                {
                    Dependency formDep = new Dependency();
                    formDep.ItemId = new ItemIdentifier(guid.ToString(), ProviderIDCollection.formItemProviderGuid);
                    formDep.Name = "Form from form picker";

                    item.Dependencies.Add(formDep);
                }
            }
        }
    }
}